/*
 * DraftScannerView.java
 *
 * Created on 7-set-2010, 19.17.11
 */

package it.shinteck.draftscanner.view;

import Lib3.DBInterface.XmlPropertiesReader;
import Lib3.DBInterface.hiTechContainer;
import it.shinteck.draftscanner.util.PDFUtil;
import java.awt.AWTEvent;
import java.awt.ActiveEvent;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.MenuComponent;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


/**
 *
 * @author vincenzo
 */
public class DraftScannerView extends javax.swing.JFrame {

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() throws Exception{

        scrollPanel = new javax.swing.JScrollPane();
        labelPanel = new javax.swing.JLabel();
        scanButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle(this.getProperties("finestra.title"));
        setMinimumSize(new java.awt.Dimension(435, 300));

        scrollPanel.setToolTipText(this.getProperties("scrollPanel.toolTip"));
        scrollPanel.setAutoscrolls(true);
        scrollPanel.setName("imagePanel"); // NOI18N

        labelPanel.setIcon(new ImageIcon(this.image));
        labelPanel.setToolTipText(this.getProperties("labelPanel.toolTip"));
        labelPanel.setAutoscrolls(true);
        scrollPanel.setViewportView(labelPanel);

        scanButton.setIcon(new javax.swing.ImageIcon(getClass().getResource(this.getProperties("scan.icon")))); // NOI18N
        scanButton.setText(this.getProperties("scan.label"));
        scanButton.setToolTipText(this.getProperties("scan.toolTip"));
        scanButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try{
                    scanButtonActionPerformed(evt);
                }catch(Exception e){
                    JOptionPane.showMessageDialog(new JPanel(), e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource(this.getProperties("cancella.icon")))); // NOI18N
        cancelButton.setText(this.getProperties("cancella.label"));
        cancelButton.setToolTipText(this.getProperties("cancella.toolTip"));
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        //imposto la griglia
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(scrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(scanButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(scanButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void scanButtonActionPerformed(java.awt.event.ActionEvent evt) throws Exception{
        this.scan();
    }

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {
        this.closeFrame();
    }


    // Variables declaration - do not modify
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel labelPanel;
    private javax.swing.JButton scanButton;
    private javax.swing.JScrollPane scrollPanel;
    // End of variables declaration


    /*---------------v.mangiapanello----------------------*/
    private hiTechContainer hitechCont;
    private XmlPropertiesReader xmlProps;
    private Image image;
    private HashMap<String, String> info;
    private byte[] pdfDOC;
    private String imageFile;

    public DraftScannerView(hiTechContainer hitechCont, Image image, HashMap<String, String> info, String imageFile) throws Exception{
        if(hitechCont!=null){
            this.hitechCont=hitechCont;
            this.xmlProps=hitechCont.getXmlProps();
        }
        this.info=info;
        this.image=image;
        this.imageFile=imageFile;
        initComponents();
    }

    public void scan() throws Exception{
        
            PDFUtil pdf=new PDFUtil();
        
        if (this.info == null || this.info.isEmpty()) {
            //creo un pdf senza metadata
            this.pdfDOC=pdf.creaPDF(this.imageFile, null);
        }else{
            //creo un pdf con i metadata: info
            this.pdfDOC=pdf.creaPDF(this.imageFile, this.info);
        }
        this.closeFrame();
    }

    public byte[] getByte(){
        return this.pdfDOC;
    }

    /*
     * Chiude la finestra attuale
     */
    public void closeFrame(){
        this.dispose();
    }

    public synchronized void hiTechStartModal() {
        if (isVisible() && !isShowing()) {
            Container parent = getParent();
            while (parent != null) {
                if (parent.isVisible() == false) {
                    parent.setVisible(true);
                }
            }
            parent = parent.getParent();
        }

        try {
            if (SwingUtilities.isEventDispatchThread()) {
                EventQueue theQueue = getToolkit().getSystemEventQueue();
                while (isVisible()) {
                    // This is essentially the body of EventDispatchThread
                    AWTEvent event = theQueue.getNextEvent();
                    Object src = event.getSource();
                    // can't call theQueue.dispatchEvent, so I pasted its body here
                    if (event instanceof ActiveEvent) {
                        ((ActiveEvent) event).dispatch();
                    } else if (src instanceof Component) {
                        ((Component) src).dispatchEvent(event);
                    } else if (src instanceof MenuComponent) {
                        ((MenuComponent) src).dispatchEvent(event);
                    } else {
                        System.err.println("unable to dispatch event: " + event);
                    }
                }
            } else {
                while (isVisible()) {
                    wait();
                }
            }
        } catch (InterruptedException e) {
        }
    }

    /**
     * Recupera il valore corrispondente alla chiave specificata nel file di properties
     * Il file di properties può essere standard java o personalizzato secondo il formato Hitech
     * @param key, la chiave richiesta
     * @return il valore per quella chiave
     */
    private String getProperties(String key) throws  Exception{
        if (xmlProps == null || hitechCont == null) {
            Properties props = new Properties();
            props.load(new FileInputStream("Properties.properties"));
            return props.getProperty(key);
        } else {
            return xmlProps.leggiStr(key);
        }
    }
}
